import path from 'path';
import fs from 'fs';
import context from './context';
import transformMain from './transformMain';

export default function* getPackageRoute(packageInfo, base = '.') {
  const { choerodonConfig: { modules } } = context;
  if (packageInfo) {
    const { main, name, routeName } = packageInfo;
    const rName = routeName || name;
    let rMain = base !== '.'
      ? main
      : transformMain(main);
      /** 如果是index 文件 未避免后缀有可能非.js,进行下面步骤.
       * 因为最终使用 import './react' 可以直接导入 无需再写成  import './react/index.js'
       * */
    if (typeof rMain === 'string' && /(\\|\/)index\.(ts|js|tsx|jsx)/.test(rMain)) {
      rMain = rMain.replace(/(\\|\/)index\.(ts|js|tsx|jsx)/, '');
    }

    const rPath = path.join(base !== '.' ? '/node_modules' : '', base, rMain);
    yield fs.promises.access(rPath);
    return { [rName]: rPath };
  }

  return undefined;
}
